<template>
    <div ref="editorContainer" class="monaco-editor"></div>
</template>

<script setup>
import { ref, shallowRef, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as monaco from 'monaco-editor'

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    },
    language: {
        type: String,
        default: 'JavaScript'
    },
    options: {
        type: Object,
        default: () => ({})
    }
})

const emit = defineEmits(['update:modelValue', 'change'])

const editorContainer = ref(null)
const editor = shallowRef(null)
let preventEmit = false

// 创建编辑器实例
const createEditor = async () => {
    if (!editorContainer.value) return

    try {
        await nextTick()

        editor.value = monaco.editor.create(editorContainer.value, {
            value: props.modelValue,
            language: props.language,
            theme: 'vs-dark',
            automaticLayout: true,
            minimap: { enabled: false },
            scrollBeyondLastLine: false,
            fontSize: 14,
            lineNumbers: 'on',
            ...props.options
        })

        // 监听内容变化
        editor.value.onDidChangeModelContent(() => {
            if (!preventEmit) {
                const value = editor.value.getValue()
                emit('update:modelValue', value)
                emit('change', value)
            }
        })

        // 初始化值
        if (props.modelValue) {
            editor.value.setValue(props.modelValue)
        }
    } catch (error) {
        console.error('Failed to create Monaco editor:', error)
    }
}

// 处理窗口大小改变
const handleResize = () => {
    if (editor.value) {
        editor.value.layout()
    }
}

// 监听属性变化
watch(() => props.modelValue, (newValue) => {
    if (editor.value && newValue !== editor.value.getValue()) {
        preventEmit = true
        editor.value.setValue(newValue)
        preventEmit = false
    }
})

watch(() => props.language, (newValue) => {
    if (editor.value) {
        monaco.editor.setModelLanguage(editor.value.getModel(), newValue)
    }
})

// 生命周期钩子
onMounted(() => {
    createEditor()
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    if (editor.value) {
        editor.value.dispose()
    }
})
</script>

<style>
.monaco-editor {
    width: 100%;
    height: 100%;
    min-height: 200px;
}
</style>